<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>Read Folder and Files</title>
</head>

<body>
<input type="file" id="fileInput" webkitdirectory directory multiple/>
<script>
    class FileTreeNode {
        constructor() {
            // 父级文件夹名称，初始化为null，可以根据实际情况赋值
            this.parentFileName = null;
            // 当前文件夹名称，初始为空字符串，后续按需赋值
            this.fileName = '';
            // 当前文件夹中文件数据，使用JavaScript的对象（类似Java中的Map）来模拟键值对，初始为空对象
            this.nameUrlMap = {};
            // 子级文件夹，使用数组（类似Java中的List）来存放子节点对象，初始为空数组
            this.sonFileList = [];
        }
    }

    document.getElementById('fileInput').addEventListener('change', async function (e) {
        const fileList = e.target.files;

        console.log("***********************用户上传文件夹*********************" + fileList);

//    const rootTreeNode = new FileTreeNode();
//    rootTreeNode.fileName = 'Root';
//    await buildFileTree(fileList, rootTreeNode);
//    const fileTreeJson = JSON.stringify(rootTreeNode);
//    console.log(fileTreeJson);
        // 可以在这里将fileTreeJson发送给后端或者进行其他处理
    });

    async function buildFileTree(files, folderTreeNode) {
        for (const file of files) {
            if (file.name.endsWith('/')) {
                const subFolderTreeNode = new FileTreeNode();
                subFolderTreeNode.parentFileName = folderTreeNode.fileName;
                subFolderTreeNode.fileName = file.name.slice(0, -1);
                const subFiles = Array.from(file.entry.files || []);
                await buildFileTree(subFiles, subFolderTreeNode);
                folderTreeNode.sonFileList.push(subFolderTreeNode);
            } else {
                const fileTreeNode = new FileTreeNode();
                fileTreeNode.parentFileName = folderTreeNode.fileName;
                fileTreeNode.fileName = file.name;
                fileTreeNode.nameUrlMap[file.name] = file.webkitRelativePath || file.path;
                folderTreeNode.sonFileList.push(fileTreeNode);
            }
        }
        return folderTreeNode;
    }
</script>
</body>

</html>